<template>
  <div class="app-container">
    <div class="filter-container clearfix">
      <el-select v-model="searchForm.sid" class="filter-item" clearable :loading="loading" placeholder="选择区服">
        <el-option
          v-for="item in serverList"
          :key="item.sid"
          :label="item.name+'('+item.sid+')'"
          :value="item.sid"
        >
        </el-option>
      </el-select>
      <el-input v-model="searchForm.param" class="filter-item" style="width: 160px;" placeholder="参数" />
      <el-date-picker v-model="searchForm.startDate" class="filter-item" type="date" style="width: 160px;" placeholder="开始时间"></el-date-picker>
      <el-date-picker v-model="searchForm.endDate" class="filter-item" type="date" style="width: 160px;" placeholder="结束时间"></el-date-picker>
      <el-button class="filter-item" type="primary" plain icon="el-icon-search" @click="handleFilter">搜索</el-button>

      <el-button v-if="checkPermission(permissionRoles.command_gm_add)" class="filter-item" type="primary" icon="el-icon-plus" @click="handleAdd">添加指令</el-button>
    </div>
    <el-table ref="table" v-loading="listLoading" :data="list" border stripe style="width: 100%;" height="705">
      <el-table-column label="ID编号" prop="id" width="90px" align="center"></el-table-column>
      <el-table-column label="服务器" prop="sidStr" width="260px" align="center"></el-table-column>
      <el-table-column label="GM指令" width="440px" align="center">
        <template slot-scope="{row}">
          <span>{{ row.command_info && row.command_info.describe ? row.command_info.describe : row.command }}</span>
        </template>
      </el-table-column>
      <el-table-column label="命令参数" prop="param" width="560px" align="center"></el-table-column>
      <el-table-column label="路由参数" prop="http_param" width="560px" align="center"></el-table-column>
      <el-table-column label="操作时间" prop="create_dt" width="160px" align="center"></el-table-column>
      <el-table-column label="状态" prop="status" align="center">
        <template slot-scope="{row}">
          <span v-if="row.status === 1">已执行</span>
          <span v-else>待执行</span>
        </template>
      </el-table-column>
      <el-table-column label="操作人" prop="create_user" align="center"></el-table-column>
    </el-table>
    <el-dialog :visible.sync="dialogVisible" title="添加指令" :close-on-click-modal="false">
      <el-form ref="dataForm" :model="dataForm" :rules="rules" label-width="100px" label-position="left">
        <el-form-item label="指令选择">
          <el-select v-model="dataForm.command" clearable filterable class="filter-item" style="width: 120px;" placeholder="指令" @change="handleSelect()">
            <el-option
              v-for="(item, index) in commandConfigs"
              :key="index"
              :label="item.describe"
              :value="item.command"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="GM指令">
          <el-input v-model="dataForm.command" class="defaut-input" placeholder="填写GM指令 如已选择则不需要填写" />
        </el-form-item>
        <el-form-item label="玩家ID">
          <el-input v-model="dataForm.player" :disabled="actorDisabled" class="defaut-input" placeholder="填写玩家ID 多个玩家用;隔开" />
        </el-form-item>
        <el-form-item label="参数" prop="http_param">
          <el-input v-model="dataForm.param" class="defaut-input" placeholder="参数 多个参数用|或空格隔开" />
        </el-form-item>
        <el-form-item label="路由参数" prop="http_param">
          <el-input v-model="dataForm.http_param" class="defaut-input" placeholder="服务的请求的param参数" />
        </el-form-item>
        <el-form-item label="服务器选择">
          <el-checkbox v-model="allServerChecked" @change="checkAllServer">显示全服</el-checkbox>
        </el-form-item>
        <div class="server-box">
          <ul class="menu-sub">
            <li
              v-for="(sgit,index) in serverGroups"
              :key="index"
            >
              <el-checkbox
                v-model="sgit.flag"
                :indeterminate="itemIndeterminate(sgit)"
                @change="(val) => handleCheckAll(val, sgit)"
              >{{ sgit.sgname }}</el-checkbox>
              <el-checkbox-group
                v-model="selectedData"
                style="padding-left: 30px;"
                @change="handleChanges(sgit)"
              >
                <el-checkbox
                  v-for="sgits in sgit.children"
                  :key="sgits.sid"
                  :label="sgits.sid"
                >{{ sgits.name }}</el-checkbox>
              </el-checkbox-group>
            </li>
          </ul>
        </div>
      </el-form>
      <div class="tr">
        <el-button type="danger" @click="dialogVisible=false">取消</el-button>
        <el-button type="primary" @click="confirmSubmit()">确定</el-button>
      </div>
    </el-dialog>
    <pagination v-show="total>0" :total="total" :page.sync="listQuery.page" :limit.sync="listQuery.limit" @pagination="getList" />
  </div>
</template>

<script>
import checkPermission from '@/utils/permission' // 权限判断函数
import waves from '@/directive/waves' // 实现点击波浪纹
import Pagination from '@/components/Pagination' // secondary package based on el-pagination
import { objectMerge } from '@/utils'
import { getServerListGroup, getServerList } from '@/api/ops'
import { handleCommand, getCommandList, getCommandConfig } from '@/api/gm'

const defaultItem = {
  command: '',
  param: '',
  player: '',
  sid: []
}
export default {
  name: 'CommandList',
  components: { Pagination },
  directives: { waves },
  data() {
    return {
      permissionRoles: this.$store.state.user.permissionRoles,
      serverList: [],
      list: [],
      total: 0,
      loading: false,
      listLoading: false,
      dataForm: Object.assign({}, defaultItem),
      actorDisabled: false,
      allServerChecked: false,
      selectedData: [],
      serverGroups: [],
      commandConfigs: [],
      rules: {},
      searchForm: {
        sid: '',
        param: '',
        startDate: '',
        endDate: ''
      },
      listQuery: {
        page: 1,
        limit: 200
      },
      dialogVisible: false
    }
  },
  created() {
    this.getList()
    this.getServerList()
  },
  methods: {
    checkPermission,
    async getList() {
      const query = objectMerge(this.searchForm, this.listQuery)
      this.listLoading = true
      const res = await getCommandList(query)
      this.listLoading = false
      this.list = res.data.items
      this.total = res.data.total
    },
    handleFilter() {
      this.getList()
    },
    async getServerList() {
      const res = await getServerList()
      this.serverList = res.data.items
    },
    async serverListGroup(val) {
      getServerListGroup({ all: val }).then(res => {
        this.serverGroups = res.data
      })
    },
    async commandConfigList(val) {
      getCommandConfig().then(res => {
        this.commandConfigs = res.data
      })
    },
    handleAdd() {
      this.dataForm = Object.assign({}, defaultItem)
      this.dialogVisible = true
      this.serverListGroup(false)
      this.commandConfigList()
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    handleSelect() {
      this.commandConfigs.forEach(item => {
        if (item.command === this.dataForm.command) {
          if (item.is_player === 0) {
            this.actorDisabled = true
          } else {
            this.actorDisabled = false
          }
          this.dataForm.param = item.param
        }
      })
    },
    confirmSubmit() {
      this.$refs['dataForm'].validate((valid) => {
        if (valid) {
          this.dataForm.sid = this.selectedData
          handleCommand(this.dataForm).then(response => {
            if (response.status) {
              this.dialogVisible = false
              this.getList()
              this.$message({
                type: 'success',
                message: '操作成功!'
              })
            } else {
              this.message.error(response.message)
            }
          })
        }
      })
    },
    // 全选
    handleCheckAll(val, item) {
      // 过滤掉没有选中的数据，item.child中不包含v时返回-1
      const next = item.children.map(item => item.sid)
      const filterArr = this.selectedData.filter(
        (v) => next.indexOf(v) === -1
      )
      this.selectedData = val ? filterArr.concat(next) : filterArr
    },
    itemIndeterminate(item) {
      const infoLists = item.children.map(ite => ite.sid)
      return (
        infoLists.some((v) => this.selectedData.indexOf(v) > -1) &&
        !infoLists.every((v) => this.selectedData.indexOf(v) > -1)
      )
    },
    // 勾选变化方法
    handleChanges(val) {
      const infoLists = val.children.map(ite => ite.sid)
      infoLists.every((v) => {
        if (this.selectedData.indexOf(v) > -1) {
          val.flag = true
        } else {
          val.flag = false
        }
      })
    },
    checkAllServer() {
      this.serverListGroup(this.allServerChecked)
    }
  }
}
</script>
